<?php

namespace app\system\controller\logic;

use app\common\model\logic\CarBtypeModel;
use app\common\model\logic\CarOrderModel;
use app\common\model\QueueModel;
use app\common\model\WechatModel;
use think\Db;
use think\helper\Time;
use think\Request;

class OrderController extends \app\system\controller\BaseController
{


    /**
     * 初始化
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    /**
     * 客户预订转行程单
     */
    public function pre2order()
    {
        $mid = $this->request->param('mid/d');
        if ($this->request->isAjax()) {
            try {
                $data = $this->request->param();
                $result = $this->validate($data, [
                    'pre_aid|预订单号' => 'require',
                    'order_start_time|出车时间' => 'require',
                    'order_end_time|收车时间' => 'require',
                    'car_sn|车辆' => 'require'
                ]);
                if (true !== $result) {
                    exception($result, 40001);
                }
                $cars = explode(',', $data['car_sn']);
                $preinfo = cms_moudle($mid)->where('aid', $data['pre_aid'])->find();
                $btypeinfo = cms_moudle(6)->where('aid',$preinfo['btype_id'])->find();
                $uid = $this->getUid();
                $order_odd = rand_number();
                if (count($cars) == $preinfo['use_car_num']) {
                    $dataList = [];
                    foreach ($data['cararr'] as $v) {
                        $btype_aid = cms_moudle(5)->where('car_sn',$v['car_sn'])->value('btype_aid');
                        $dataList[] = [
                            'mid'=>14,
                            'uid'=>$uid,
                            'car_sn' => $v['car_sn'],
                            'order_charge' => $v['order_charge'],
                            'order_advance' => $v['order_advance'],
                            'guide' => $v['guide'],
                            'guide_tel' => $v['guide_tel'],
                            'begin_time' => $v['begin_time'],
                            'order_start_time' => $data['order_start_time'],
                            'order_end_time' => $data['order_end_time'],
                            'order_start_adress' => $v['order_start_adress'],
                            'order_end_adress' => $v['order_end_adress'],
                            'diff_money'=>$v['diff_money']>0?$v['diff_money']:0,
                            'fleet_desc' => $data['fleet_desc'],
                            'order_odd' => $order_odd,
                            'btype_id' => $btypeinfo['aid'],
                            'order_phone' => $btypeinfo['btype_phone'],
                            'order_company' => $btypeinfo['company'],
                            'order_client' => $btypeinfo['title'],
                            'sum_odd' => $v['car_sn'].'-'.date('YmdHi'),
                            'btype_aid' => $btype_aid,
                            'title' => $btypeinfo['title'].'['.$v['order_start_adress'].'-'.$v['order_end_adress'].']行程单',
                        ];
                    }
                    cms_moudle(14)->saveAll($dataList);
                    cms_moudle(19)->where('aid',$data['pre_aid'])->setField('pre_status',1); //标记为已转换
                } else {
                    exception('预计出车和实际派车数量不符！', 40001);
                }
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('操作成功！', url('system/op/index', ['mid' => $data['mid']]));
        }
        $aid = $this->request->param('aid/d');
        $preinfo = cms_moudle($mid)->where('aid', $aid)->find();
        $this->assign('preinfo', $preinfo);
        return $this->fetch();
    }

    //设置驾驶员
    public function setdri()
    {
        $aid = $this->request->param('aid');
        $fleet_driver = $this->request->param('fleet_driver');
        $fleet_driver_ids = $this->request->param('fleet_driver_ids');
        if (empty($fleet_driver_ids)) {
            $this->error('请选择司机！');
        }
        $data = [
            'fleet_driver' => $fleet_driver,
            'fleet_driver_ids' => $fleet_driver_ids,
        ];
        try {
            $orderInfo = cms_moudle(14)->where('aid', $aid)->find();
            $msg = '司机指派成功!';
            if (!empty($orderInfo['fleet_driver_ids'])) {
                $msg = '更换司机成功！';
            }
            cms_moudle(14)->where('aid', $aid)->update($data);
            //模板消息
            $fleet_driver_ids = explode(',', $fleet_driver_ids);
            $uids = Db::table('car_driver')->where('aid', 'in', $fleet_driver_ids)->column('bind_uid');
            if ($uids) {
                $openids = Db::table('user_wx')->where('uid', 'in', $uids)->column('openid');
                if ($openids) {
                    foreach ($openids as $openid) {
                        $url = url('system/Index/index', '', 'html', true);
                        QueueModel::addQueue('app\common\job\Wechat',[
                            'fun'=>'tplSendCar',
                            'openid'=>$openid,
                            'url'=>$url,
                            'car_sn'=>$orderInfo['car_sn'],
                            'order_start_time'=>$orderInfo['order_start_time']
                        ]);
                    }
                }
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success($msg);
    }

    //司机确认订单
    public function orderConfirm()
    {
        try {
            $aid = $this->request->param('aid/d');
            $orderInfo = Db::table('car_order')->where('aid', $aid)->find();
            $driver = Db::table('car_driver')->where('bind_uid', $this->getUid())->find(); //当前登录司机
            $confirm = [];
            if (!empty($orderInfo['order_confirm'])) {
                $confirm = json_decode($orderInfo['order_confirm'], true);
                if (array_key_exists($driver['aid'], $confirm)) {
                    exception('该订单您已确认！', 40001);
                }
            }
            $confirm[$driver['aid']] = $driver['title'] . '[' . date('Y-m-d H:i') . ']确认了订单';
            Db::table('car_order')->where('aid', $aid)->setField('order_confirm', json_encode($confirm));
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('操作成功！');
    }

    //司机订单执行前请假
    public function orderLeave()
    {
        try {
            $config = cache('webconfig');
            $day = $config['LEVEL_DAY']; //请假日期间隔天数
            $time = time();
            $aid = $this->request->param('aid/d'); //订单ID
            $orderInfo = Db::table('car_order')->where('aid', $aid)->find();
            if (($orderInfo['order_start_time'] - $time) / 86400 <= $day) { //判断自动请假
                $lastOrderInfo = Db::table('car_order')->where('aid', '<', $aid)->where('order_status', 2)->find(); //上一笔收车订单
                if (empty($lastOrderInfo)) { //没有上一笔订单，正常请假
                    return ['code' => 2, 'msg' => '满足正常请假', 'last_time' => 0];
                } else {
                    return ['code' => 1, 'msg' => '触发设定规则，系统自动处理矿工', 'last_time' => $lastOrderInfo['order_start_time']];
                }
            } else {
                return ['code' => 2, 'msg' => '满足正常请假', 'last_time' => 0];
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

    //出车收车
    public function setstatus()
    {
        try {
            $aid = $this->request->param('aid/d');
            $orderInfo = Db::table('car_order')->where('aid', $aid)->find();
            $order_status = $this->request->param('order_status', 0);
            if ($order_status == 0) {
                if (Db::table('car_order')->where('car_sn', $orderInfo['car_sn'])->where('car_status', 1)->find()) {
                    exception('该车辆正在出车中，不能二次出车', 40001);
                }
                $time = time();
                /*
                if(($order_start_time-$time)>86400){
                    exception('离出发日期还有一天以上,防止误差，不允许执行出车！',40001);
                }
                */
                if (!$this->request->has('order_start_mm')) {
                    exception('请输入出发里程数', 40001);
                }
                if($orderInfo['fleet_driver_ids']){ //有司机才判断司机状态
                    $driverId = Db::table('car_driver')->where('bind_uid', $this->getUid())->value('aid'); //根据当前登录人取司机ID
                    $string = "find_in_set('{$driverId}',fleet_driver_ids)"; //指定的驾驶员
                    if (Db::table('car_order')->where($string)->where('car_status', 1)->find()) {
                        exception('你正在行程中不能再次出车', 40001);
                    }
                }

                $data['out_time'] = $time;
                $data['order_start_mm'] = $this->request->param('order_start_mm/f');
                //更新车辆和司机状态
                Db::table('car_driver')->where('aid','in',$orderInfo['fleet_driver_ids'])->setField('dri_status',0); //设置出车
                Db::table('car')->where('car_sn',$orderInfo['car_sn'])->setField('car_status',1);
            }
            //车辆状态0待出发 1出车中 2已收车 3已结算
            if ($order_status == 1) {
                if (!$this->request->has('order_end_mm')) {
                    exception('请输入结束里程数', 40001);
                }
                if ($this->request->param('order_end_mm/f') < $orderInfo['order_start_mm']) {
                    exception('收车里程不能小于出车里程', 40001);
                }
                $data['order_end_mm'] = $this->request->param('order_end_mm/f');
                $data['order_mileage'] = $data['order_end_mm']-$orderInfo['order_start_mm'];
                $data['back_time'] = time();
                //增加车辆里程数和车辆状态
                $carData = [
                    'car_status'=>0,
                    'car_mileage' => ['exp','car_mileage+'.$data['order_mileage']],
                ];
                Db::table('car_driver')->where('aid','in',$orderInfo['fleet_driver_ids'])->setField('dri_status',2); //设置空闲
                Db::table('car')->where('car_sn',$orderInfo['car_sn'])->update($carData);
            }
            $data['car_status'] = $order_status + 1;
            Db::table('car_order')->where('aid', $aid)->update($data);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('操作成功！');
    }

    //订单延期
    public function delay()
    {
        try {
            $aid = $this->request->param('aid/d');
            $day = $this->request->param('day/d');
            if ($day <= 0) {
                exception('延期天数必须大于0', 40001);
            }
            $orderInfo = Db::table('car_order')->where('aid', $aid)->find();
            $order_delay = (int)$orderInfo['order_delay'] + (int)$day;
            $order_end_time = (int)$orderInfo['order_end_time'] + (int)$day * 86400;
            $data = [
                'order_delay' => $order_delay,
                'order_end_time' => $order_end_time
            ];
            Db::table('car_order')->where('aid', $aid)->update($data);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('延期成功！');
    }

    //结算单显示
    public function spend()
    {
        $aid = $this->request->param('aid/d');
        $data = cms_moudle(14)->spend($aid);
        return $data;
    }

    //修改结算单
    public function spendDo()
    {
        try {
            $data = $this->request->param();
            $order_charge = $this->request->param('order_charge/f');
            $order_advance = $this->request->param('order_advance/f'); //定金
            $order_pay = $this->request->param('order_pay/f'); //收款
            $discount_money = $this->request->param('discount_money/f'); //优惠金额
            $data['order_q'] = ($order_charge - $order_advance - $order_pay-$discount_money);
            if ($data['order_q'] < 0) {
                exception('金额计算错误！', 40001);
            }
            if($data['order_fuel']>0 || $data['order_l']>0){
                if((float)$data['order_fuel']<=0 || (float)$data['order_l']<=0){
                    exception('加油升数和加油费用必填',40001);
                }
            }
            $actionName = get_field_value('user','name',['uid'=>$this->getUid()]);
            $data['reckoner'] = $actionName; //结算人
            $data['car_status'] = 3; //结算状态
            if($data['order_q']==0){ //补充清算人
                $data['square'] = $actionName;
            }
            $carOrderModel = new CarOrderModel();
            $carOrderModel->isUpdate(true)->allowField(true)->save($data);
            //插入支付金额
            $payData=[
                'order_id'=>$data['aid'],
                'order_title'=>$data['title'],
                'car_sn'=>$data['car_sn'],
                'pay_title'=>'['.date('Y-m-d H:i:s').']进行了单车结算',
                'pay_time'=>time(),
                'action_name'=>$actionName,
            ];
            $payData['money_bala'] = $carOrderModel->getData('order_bala');
            $payData['pay_money'] = $order_advance+$order_pay; //定金+回款
            $payData['money_discount'] = $discount_money; //优惠金额
            Db::table('car_order_pay')->insert($payData);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('添加成功！', url('system/op/index', ['mid' => $data['mid'],'tpl'=>'index_spend']));
    }
    //清除司机
    public function delleave(){
        try{
            $aid = $this->request->param('aid/d');
            $data=[
                'fleet_driver'=>'',
                'fleet_driver_ids'=>'',
                'order_confirm'=>''
            ];
            cms_moudle(14)->where('aid',$aid)->update($data);
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('操作成功!');
    }
    //设置司机预借现金
    public function setsjpremoney(){
        try{
            $aid = $this->request->param('aid/d');
            $sj_pre_money = $this->request->param('sj_pre_money/f');
            cms_moudle(14)->where('aid',$aid)->setField('sj_pre_money',$sj_pre_money);
        }catch (\Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('操作成功！');
    }

    /**
     * 行程单付款
     */
    public function paymoney(){
        $rangdate=$this->request->param('rangdate','');
		$is_gua=$this->request->param('is_gua','-1');
        $customer = $this->request->param('customer');
        $rangdatearr = explode('~',$rangdate);
        $begin = strtotime($rangdatearr[0].' 0:00:00');
        $end = strtotime($rangdatearr[1].' 23:59:59');
        $map['car_status']=['>',1];
        //$map['btype_aid']=1; //自己人
        $orderQ = $this->request->param('order_q',1); //默认欠款用户
        if($orderQ==1){
            $map['order_q']=['>',0];
        }else{
            $map['order_q']=0;
        }
        if(!empty($rangdate)){
            $map['back_time']=['between',[$begin,$end]];
        }
        if(!empty($customer)){ //查询客户
            $btypeids = cms_moudle(6)->where('title','like','%'.$customer.'%')->column('aid');
            if(!empty($btypeids)){
                $map['btype_id'] = ['in',$btypeids];
            }
        }
        $orderModel = new CarOrderModel();
        $list = $orderModel
            ->field('btype_id,sum(order_q) as sum_order_q,sum(order_charge) as sum_order_charge')
            ->where($map)
            ->group('btype_id')
            ->select(); //自己得收车订单
        //echo $orderModel->getLastSql();
        if(!$list->isEmpty()){
            $list=$list->toArray();
            $btype_ids = array_column($list,'btype_id');
            $btypelist = cms_moudle(6)->where('aid','in',$btype_ids)->column('*','aid');
            $sum=['sum_order_q'=>0,'sum_order_charge'=>0];
            foreach($list as $k=>$v){
                $list[$k]['btype'] = $btypelist[$v['btype_id']];
				if($is_gua==1){ //挂账
					if($v['sum_order_q']<=$btypelist[$v['btype_id']]['credit_line']){
						unset($list[$k]);
					}
				}
				if($is_gua==2){ //正常
					if($v['sum_order_q']>$btypelist[$v['btype_id']]['credit_line']){
						unset($list[$k]);
					}
				}
                $sum['sum_order_q'] += $v['sum_order_q'];
                $sum['sum_order_charge'] += $v['sum_order_charge'];
            }
        }
        $this->assign('order_q',$orderQ);
        $this->assign('sum',$sum);
        $this->assign('rangdate',$rangdate);
		$this->assign('is_gua',$is_gua);
        $this->assign('list',$list);
        return $this->fetch();
    }
    //和客户结算
    public function dopaymoney(){
        $orderModel = new CarOrderModel();
        if($this->request->isAjax()){
            try{
                $data = $this->request->param();
                if(empty($data['order'])){
                    exception('参数错误！',40001);
                }
                $order = $data['order'];
                $dataList=[];
                $aids = [];
                foreach($order as $key=>$value){
                    $orderInfo = $orderModel->where('aid',$key)->find();
                    $orderPay = $orderInfo['order_pay']+$value['pay_money'];
                    $orderQ = $orderInfo['order_charge']-$orderInfo['order_advance']-$orderPay-$value['discount_money'];
                    $discountMoney = $value['discount_money'];
                    $actionName = get_field_value('user','name',['uid'=>$this->getUid()]);
                    $dataList[]=[
                        'aid'=>$key,
                        'order_pay'=>$orderPay,
                        'order_q'=>$orderQ,
                        'discount_money'=>$discountMoney,
                        'square'=>$actionName //清算人
                    ];
                    $aids[]=$key;
                    if($value['pay_money']>0){ //回款
                        Db::table('car_order_pay')->insert([
                            'order_id'=>$key,
                            'order_title'=>$orderInfo['title'],
                            'car_sn'=>$orderInfo['car_sn'],
                            'pay_title'=>$actionName.'['.date('Y-m-d H:i:s').']收取了'.$value['pay_money'].'元回款',
                            'pay_money'=>$value['pay_money'],
                            'money_bala'=>0,
                            'pay_time'=>time(),
                            'action_name'=>$actionName,
                        ]);
                    }
                }
                if(!empty($dataList)){
                    $orderModel->saveAll($dataList);
                }
            } catch (\Exception $e){
                $this->error($e->getMessage());
            }
            ///http://car.180vip.cn/system/logic.order/dopaymoney.html?btype_id=49&order_q=0&tpl=viewpaymoney&aids=49
            $this->success('操作成功！','/system/logic.order/dopaymoney.html?btype_id='.$this->request->param('btype_id').'&order_q=0&tpl=viewpaymoney&aids='.implode(',',$aids));
        }
        $btype_id=$this->request->param('btype_id/d');
        $rangdate=$this->request->param('rangdate','');
        $rangdatearr = explode('~',$rangdate);
        $aids = $this->request->param('aids');
        if(!empty($aids)){
            $map['aid']=['in',$aids];
        }else{
            $map['car_status']=['>',1];
            $map['btype_id']=$btype_id;
            $map['btype_aid']=1;
            $begin = strtotime($rangdatearr[0].' 0:00:00');
            $end = strtotime($rangdatearr[1].' 0:00:00');
            $orderQ = $this->request->param('order_q',1); //默认欠款用户
            if($orderQ==1){
                $map['order_q']=['>',0];
            }else{
                $map['order_q']=0;
            }
            if(!empty($rangdate)){
                $map['back_time']=['between',[$begin,$end]];
            }
        }
        $list = $orderModel->where($map)->select(); //自己得收车订单
        if(!$list->isEmpty()){
            $list=$list->toArray();
            $btypeinfo = cms_moudle(6)->where('aid',$btype_id)->find(); //客户信息
            $sum=['sum_order_q'=>0,'sum_order_charge'=>0];
            foreach($list as $k=>$v){
                $sum['sum_order_q'] += $v['order_q'];
                $sum['sum_order_charge'] += $v['order_charge'];
            }
        }
        $tpl = $this->request->has('tpl')?$this->request->param('tpl'):'';
        $this->assign('btypeinfo',$btypeinfo);
        $this->assign('list',$list);
        $this->assign('sum',$sum);
        return $this->fetch($tpl);
        
    }

    /**
     * 对冲列表
     */
    public function hedge(){
        $btypeModel = new CarBtypeModel();
        $orderModel = new CarOrderModel();
        if($this->request->isAjax()){
            try{
                $btype_aid = $this->request->param('btype_aid/d');
                $map['car_status']=['>',1];
                $map['btype_aid']=$btype_aid;
                $map['is_hedge']=0; //是否对冲过
                $list = $orderModel->where($map)->select();
                $dataList=[];
                foreach($list as $v){
                    $dataList[]=[
                        'aid'=>$v['aid'],
                        'order_q'=>0,
                        'order_pay'=>$v['order_charge']-$v['order_advance']->$v['discount_money'],
                        'car_status'=>3,
                        'is_hedge'=>1,
                    ];
                }

                $map1['car_status']=['>',1];
                $map1['btype_aid']=1;
                $map1['btype_id']=$btype_aid;
                $map1['is_hedge']=0;
                $list = $orderModel->where($map1)->select();
                foreach($list as $v){
                    $dataList[]=[
                        'aid'=>$v['aid'],
                        'order_q'=>0,
                        'order_pay'=>$v['order_charge']-$v['order_advance']->$v['discount_money'],
                        'car_status'=>3,
                        'is_hedge'=>1,
                    ];
                }
                if(!empty($dataList)){
                    $orderModel->saveAll($dataList);
                }
            } catch (\Exception $e){
                $this->error($e->getMessage());
            }
            $this->success('操作成功！');
        }
        $btypeinfo2 = $btypeModel->where('aid',1)->find()->toArray();
        $map['car_status']=['>',1];
        $map['btype_aid']=['>',1];
        $map['is_hedge']=0; //是否对冲过
        $list = $orderModel
            ->where($map)
            ->group('btype_aid')
            ->column("btype_aid,count(*) as count,sum(diff_money) as sum_order_charge,sum(order_advance) as sum_order_advance,
                            sum(order_pay) as sum_order_pay,sum(discount_money) as sum_discount_money",'btype_aid');
        if(!empty($list)){
            foreach($list as $k=>$v){
                $list[$k]['item1'] = $orderModel
                    ->where($map)
                    ->where('btype_aid',$v['btype_aid'])
                    ->select();
                $map1['car_status']=['>',1];
                $map1['btype_aid']=1;
                $map1['btype_id']=$k;
                $map1['is_hedge']=0;
                $list[$k]['order_q1'] =$v['sum_order_charge']-$v['sum_order_advance']-$v['sum_order_pay']-$v['sum_discount_money'];
                $list[$k]['btypeinfo1'] = $btypeModel->where('aid',$k)->find();
                $list[$k]['btypeinfo2'] = $btypeinfo2;
                $right = $orderModel
                    ->field('count(*) as count,sum(order_charge) as sum_order_charge,sum(order_advance) as sum_order_advance,
                                   sum(order_pay) as sum_order_pay,sum(discount_money) as sum_discount_money')
                    ->where($map1)
                    ->group('btype_id')
                    ->find();
                if(empty($right)){
                    unset($list[$k]);
                }else{
                    $list[$k]['item2'] = $orderModel->where($map1)->select();
                    $list[$k]['right'] = $right;
                    $list[$k]['order_q2'] = $right['sum_order_charge']-$right['sum_order_advance']-$right['sum_order_pay']-$right['sum_discount_money'];
                }
            }
        }else{
            $list=[];
        }
        $this->assign('list',$list);
        return $this->fetch();
    }
    //插入短途行程
    public function insertorder(){
        if($this->request->isAjax()){
            $data = $this->request->param();
            $orderinfo = cms_moudle(14)->where('aid',$data['aid'])->find();
            cms_moudle(14)->isUpdate(true)->allowField(true)->save($data);
            //发送模板消息
            $fleet_driver_ids = explode(',', $orderinfo['fleet_driver_ids']);
            $uids = Db::table('car_driver')->where('aid', 'in', $fleet_driver_ids)->column('bind_uid');
            if ($uids) {
                $openids = Db::table('user_wx')->where('uid', 'in', $uids)->column('openid');
                if ($openids) {
                    foreach ($openids as $openid) {
                        $url = url('system/Index/index', '', 'html', true);
                        QueueModel::addQueue('app\common\job\Wechat',[
                            'fun'=>'tplSendCar',
                            'openid'=>$openid,
                            'url'=>$url,
                            'car_sn'=>$orderinfo['car_sn'],
                            'order_start_time'=>$orderinfo['order_start_time']
                        ]);
                    }
                }
            }
            $this->success('操作成功！','system/op/index?mid=14&tpl=insert_order&short_status=1');
        }
        $aid = $this->request->param('aid/d');
        $orderinfo = cms_moudle(14)->where('aid',$aid)->find();
        $this->assign('orderinfo',$orderinfo);
        return $this->fetch();
    }
    //退回结算单
    public function backstatus(){
        $aid = $this->request->param('aid/d');
        cms_moudle(14)->where('aid',$aid)->setField('car_status',2);
        Db::table('car_order_pay')->where('order_id',$aid)->delete();
        $this->success('操作成功！');
    }
}
